/**
 * 
 */
package fr.cephb.joperon.webapp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.sql.DataSource;

/**
 * @author operon
 *
 */
public class OperonSessionListener implements HttpSessionListener {
	@Resource(name="jdbc/OperonDS")
	private DataSource datasource;

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionCreated(HttpSessionEvent event)
		{
		HttpSession session=event.getSession();
		if(session==null) return;
		session.getServletContext().log("creation of a new id "+session.getId());
		}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent event)
		{
		HttpSession session=event.getSession();
		if(session==null) return;
		String id= session.getId();
		if(id==null) return;
		session.getServletContext().log("destroying session "+id);
		Connection con=null;
		try {
			con= this.datasource.getConnection();
			PreparedStatement pstmt= con.prepareStatement("delete from operon.document where session_id=?");
			pstmt.setString(1, id);
			int n= pstmt.executeUpdate();
			session.getServletContext().log("deleted "+n+" rows");
			pstmt.close();
			} 
		catch (Exception e)
			{
			System.err.println(e.getMessage());
			}
		finally
			{
			if(con!=null) try{con.close();} catch(SQLException err) {}
			}
		}

}
